<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem">
      <template v-slot:customTableHeader>
        <tabs ref="tabsStudent" :tabsList="tabsList" @switchTab="switchTab"></tabs>
      </template>
    </tablePaging>
  </div>
  <fileImport v-model:importVisible="importVisible" :importItem="importItem" @onSuccess="onSuccess" @onError="onError" />
  <el-dialog v-model="addOrUpdateVisible" :title="title" :before-close="handleClose">
    <div>
      <el-form ref="studentRef" label-width="140px" :model="form" :rules="rules">
        <el-form-item label="批次号" prop="batchNum">
          <el-input v-model="form.batchNum" placeholder="请输入批次号" style="width: 100%" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" style="width: 100%"></el-input>
        </el-form-item>
<!--        <el-form-item v-if="form.status !== '1'" label="考试日期" prop="lineDate">-->
<!--          <el-date-picker style="width: 100%" v-model="form.lineDate" type="date" placeholder="考试日期"-->
<!--            value-format="YYYY-MM-DD">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="考试科目" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择科目" class="select-style" clearable filterable
            @change="selectChange" :disabled="isPass">
            <el-option v-for="item in courseListOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" :maxlength="11" placeholder="请输入手机号" style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addOrUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="studentConfirm"> 确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="configVisible" title="指定企业" :before-close="handleClose">
    <div>
      <el-form ref="configRef" label-width="140px" :model="configForm" :rules="rules">
        <el-form-item label="企业名称" prop="entId">
          <el-select v-model="configForm.entId" placeholder="请选择企业名称" class="select-style" clearable filterable>
            <el-option v-for="item in entList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="configVisible = false">取 消</el-button>
        <el-button type="primary" @click="configConfirm"> 确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import tabs from '@/views/common/component/tabs'
import tablePaging from '@/views/common/component/table-paging'
import fileImport from '@/views/common/component/fileImport'
import { onBeforeMount, onMounted, reactive, ref, watch } from 'vue'
import {
  tableItem,
  operationItem,
  studentEditApi, entSetApi, studentDelApi, studentDetailApi, courseListApi, bankTypeListApi
} from './const.js'
import { ElMessage } from 'element-plus'
import { validateCreditCode } from '../../../../utils/validate'
import { clearForm } from '../../../../utils'
import { orgListApi } from '../../org/enterprise/const'
import useUserStore from '@/store/modules/user'
import {treeSubject} from '../../course/const'
const userStore = useUserStore()
const statusRem = ref(0)
const tabsList = ref([
  { name: '全部', status: '0' },
  { name: '已通过', status: '2' },
  { name: '未审核', status: '1' },
  { name: '已到期', status: '3' },
])
//如果账号类型是企业，那么只能看到已通过，其他两个看不到
if (userStore.typeCode == "enterprise") {
  tabsList.value = [{ name: '已通过', status: '2' }];
}

// //机构登录看不到题库类型
// if (userStore.typeCode == 'association') {
//   tableItem.column[9].width = 0
// }

const { proxy } = getCurrentInstance()
const title = ref('');
const tabsStudent = ref('');
// tabsStudent
const isAdd = ref(false);
const isPass = ref(false);
const addOrUpdateVisible = ref(false);
const configVisible = ref(false)
const studentRef = ref('')
const configRef = ref('')
const courseListOptions = ref([])
const entList = ref([])
const selectIdList = ref([])
const handleClose = () => {
  reset();
  addOrUpdateVisible.value = false
  configVisible.value = false
};
const importVisible = ref(false)
const importItem = reactive({
  downUrl: '/student/download/excl',//文件下载地址
  upUrl: '/student/import/excl',//文件上传地址
  blob: true,//二进制文件下载
  fileDown() { },//自定义文件下载方法 如果传入下载地址会失效 如果都不传会返回一个fileDown函数 自己@fileDown接收
  downTitle: '',//下载标题 默认1、模板下载
  downButtonText: '',//下载按钮 下载
  upButtonText: '',//上传按钮 上传
  upTitle: ''//上传标题 默认2、表格上传
})

const onError = (file) => { }
const form = reactive({
  id: '',
  conCourseId: '',
  batchNum: '',
  name: '',
  idCard: '',
  lineDate: '',
  courseId: '',
  phone: '',
  statusList: '',
},)

const configForm = reactive({
  entId: '',
  idList: []
})

const rules = ({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [{ required: true, validator: validateCreditCode, trigger: 'blur' }],
  lineDate: [{ required: true, message: '请选择考试日期', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择科目', trigger: 'blur' }],
  phone: [{ required: false, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  entId: [{ required: true, message: '请选择企业名称', trigger: 'blur' }],
})

watch(() => { return tableItem.pageInfo.request.courseId || tableItem.pageInfo.request.categoryId}, () => {
  let courseId = tableItem.pageInfo.request.courseId
  let categoryId = tableItem.pageInfo.request.categoryId
  if (courseId || categoryId) {
    tableItem.pageInfo.request.courseBankTypeName = ''
    setBankTypeListOptions(categoryId, courseId)
  } else {
    tableItem.pageInfo.request.courseBankTypeName = ''
    operationItem.SearchItem[4].options = []
  }
}, { immediate: true, deep: false })
onBeforeMount(() => { initRequest(); statusRem.value = tabsList.value[0].status })
const getUserInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
onMounted(() => {
  initTreeSubject()
  // setCourseListOptions();
  const disabledColumn = new Set();
  if (getUserInfo) {
    // 机构institution 协会association 企业enterprise
    //企业不显示机构
    if (getUserInfo.typeCode != 'admin') {
      operationItem.SearchItem[4].closeSearch = true
      // tableItem.column[8].width = 0
      disabledColumn.add("题库类型")
      // tableItem.column[10].width = 0
      statusRem.value == 0 ? operationItem.menuArray[3].show = false : ''
      // 机构institution 协会association 企业enterprise
    }
    if (getUserInfo.typeCode == 'enterprise') {
      // tableItem.column[5].width = 0
      // tableItem.column[9].width = 0
      // tableItem.column[10].width = 0;
      disabledColumn.add("所属企业")
      disabledColumn.add("状态")
      disabledColumn.add("操作")
    }
  }
  const displayedColumn = []
  tableItem.column.forEach( (column) => {
    if (!disabledColumn.has(column.label)) {
      displayedColumn.push(column)
    }
  })
  tableItem.column = displayedColumn
})

const onSuccess = (file) => {
  if (tabsStudent.value) {
    tabsStudent.value.switchTabChange(0)
  }
  tableItem.pageInfo.request.statusList = [1, 2, 3]
  tableItem.pageInfo.paging()
}
// tab栏回调
const switchTab = (item, index) => {
  const statusMap = {
    '已通过': '2',
    '未审核': '1',
    '已到期': '3'
  };
  statusRem.value = item.status || 0
  if (item.status == 0) {
    tableItem.pageInfo.request.statusList = [1, 2, 3]
    // console.log(item.name in statusMap, 'item.name in statusMap')
  } else {
    if (item.name in statusMap) {
      tableItem.pageInfo.request.statusList = [statusMap[item.name]];
    }
  }
  tableItem.pageInfo.paging()
  //为审核展示操作栏
  if (getUserInfo) {
    // 机构institution 协会association 企业enterprise
    //企业不显示机构
    if (item.status == 0) { tableItem.column[9].width = 'auto'; } else {
      tableItem.column[9].width = 0;
    }
    if (getUserInfo.typeCode != 'admin') {
      if (item.status == 1 || item.status == 0) {
        tableItem.column[10].width = 120;
      } else {
        tableItem.column[10].width = 0;
      }
      item.status == 1 ? operationItem.menuArray[3].show = true : operationItem.menuArray[3].show = false
    }

  }
}

function initRequest() {
  tableItem.pageInfo.request.statusList = [1, 2, 3]
}

// 搜索
operationItem.menuArray[0].handle = () => {
  clickSearch()
}
// 导入
operationItem.menuArray[1].handle = () => {
  importVisible.value = true
}
// 指定企业
operationItem.menuArray[2].handle = () => {
  clickConfig('point')
}
// 批量删除
operationItem.menuArray[3].handle = () => {
  clickConfig('del')
}
//修改
tableItem.btnArray[0].handle = (row) => {
  clickEdit(row)
}
// 删除
tableItem.btnArray[1].handle = (row) => {
  studentDel({ idList: [row.conCourseId] }, '确定删除' + '【' + row.name + '】这条数据吗？')
}
const studentDel = (requestDel, text) => {
  proxy.$modal.confirm(text).then(() => {
    studentDelApi(requestDel).then(res => {
      ElMessage.success(res.msg || '操作成功'); tableItem.pageInfo.paging()
    })
  })
}
//选择
tableItem.selectChange = (selection) => {
  selectIdList.value = selection.map(item => item.conCourseId)
}

function clickSearch() {
  tableItem.pageInfo.paging()
}

function clickConfig(type) {
  if (selectIdList.value.length > 0) {
    configForm.idList = selectIdList.value
    switch (type) {
      case 'del': studentDel(configForm, "确定删除" + selectIdList.value.length + '人')
        break;
      case 'point':
        proxy.resetForm("configRef");
        reset()
        configVisible.value = true
        let dataRequest = {
          nickName: '',
          typeCodeList: ['enterprise']
        }
        orgListApi(dataRequest).then(res => {
          const orgList = res.rows || res.data
          entList.value = orgList.map(item => ({ label: item.nickName, value: item.userId }))
        })
        break;
      default: ''
    }
  } else {
    ElMessage.error('请先选择学员!')
  }
}
function selectChange() {
  console.log('courseListOptions', courseListOptions)
  console.log('from', form)
}

const initTreeSubject = () => {
  treeSubject({}).then(res=>{
    let searchItem = operationItem.SearchItem[3];
    searchItem.options = res.rows
    searchItem.props = {value: 'id', label: 'name', checkStrictly: true}
    searchItem.change = function(){
      let request = tableItem.pageInfo.request
      let subjectArray = request.subjectArray
      request.categoryId = ""
      request.subjectId = ""
      request.courseId = ""
      if (subjectArray){
        if (subjectArray.length == 1) {
          request.subjectId = subjectArray[0]
        }
        if (subjectArray.length == 2) {
          request.categoryId = subjectArray[1]
        }
        if (subjectArray.length == 3) {
          request.courseId = subjectArray[2]
        }
      }
    }
  })
}

function setCourseListOptions() {
  let dataRequest = {
    levelNum: 3,
    parentId: '',
    disableFlag: 0
  }
  courseListApi(dataRequest).then(res => {
    courseListOptions.value = res.rows.map(item => ({ label: item.name, value: item.id }))
  })
}

function setBankTypeListOptions(categoryId, courseId) {
  let dataRequest = {
    name: '',
    orderNum: '',
    courseId: categoryId,
    courseChildId: courseId
  }
  bankTypeListApi(dataRequest).then(res => {
    operationItem.SearchItem[4].options = res.rows.map(item => ({ label: item.name, value: item.name }))
  })
}

function clickEdit(row) {
  proxy.resetForm("studentRef");
  addOrUpdateVisible.value = true
  isAdd.value = false
  title.value = "修改学员"
  setCourseListOptions()
  if (row.status === '2') {
    isPass.value = true
  } else {
    isPass.value = false
  }
  studentDetailApi({ id: row.id, conCourseId: row.conCourseId }).then(res => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
  });
}
const configConfirm = async () => {
  if (!configRef.value) return
  await configRef.value.validate((valid, fields) => {
    if (!valid) { return }
    entSetApi(configForm).then(res => {
      ElMessage.success('指定成功');
      configVisible.value = false;
      tableItem.pageInfo.paging()
    })
  })
}

const studentConfirm = async () => {
  if (!studentRef.value) return
  await studentRef.value.validate((valid, fields) => {
    if (!valid) { return }
    if (isAdd.value) {
      // studentAddApi(form).then(res => {
      //   ElMessage.success('新增成功');
      //   addOrUpdateVisible.value = false;
      //   tableItem.pageInfo.paging()
      // })
    }
    if (!isAdd.value) {
      studentEditApi(form).then(res => {
        ElMessage.success('修改成功');
        addOrUpdateVisible.value = false;
        tableItem.pageInfo.paging()
      })
    }
  })
}

function reset() {
  clearForm(form)
  // clearForm(configForm)
  configForm['entId'] = '';
}

</script>

<style>
.select-style {
  width: 100%;
}

.select-style .el-input__inner {
  width: 736px;
}
</style>
